<template>
  <!-- <div class="container mx-auto p-4"> -->
  <div class="bg-slate-50 h-screen">
    <div class="shopping-cart rounded-lg">
      <div class="flex items-center justify-between mb-4">
        <div class="flex items-center">
          <h1 class="text-2xl font-bold pl-6">购物车</h1>
          <span class="text-sm text-gray-500">({{ cartItemCount }})</span>
        </div>
        <button
          @click="toggleManageMode"
          class="text-black-500 hover:underline p-6"
        >
          {{ manageMode ? "退出管理" : "管理" }}
        </button>
      </div>
      <van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
        <div
          class="product mb-3 flex items-center pb-0.5 px-1.5 mx-5 bg-white rounded-lg"
          v-for="product in cartItems"
          :key="product.id"
        >
          <van-checkbox :name="product.id" class="mr-2"> </van-checkbox>
          <img
            :src="product.cover"
            alt="Product cover"
            class="w-16 h-16 object-cover mr-4 rounded-lg"
          />
          <div class="flex-1">
            <h3 class="text-lg font-semibold">{{ product.name }}</h3>
            <p class="text-gray-600">{{ product.description }}</p>
            <p class="text-red-500 text-xl">{{ getCurrency(product.price) }}</p>
          </div>
          <div class="flex items-center">
            <button
              @click="toggleEditMode"
              class="text-gray-500 hover:text-gray-700"
            >
              <span v-if="!isEditMode">×</span>
            </button>
            <button
              @click="decreaseQuantity(product)"
              class="text-gray-500 hover:text-gray-700"
            >
              <span v-if="isEditMode">-</span>
            </button>
            <span class="mx-2 min-w-[20px] text-center inline-block">{{
              product.quantity
            }}</span>
            <button
              @click="increaseQuantity(product)"
              class="text-gray-500 hover:text-gray-700"
            >
              <span v-if="isEditMode">+</span>
              <span v-else></span>
            </button>
          </div>
          <button
            v-if="manageMode"
            @click="removeFromCart(product.id)"
            class="text-red-500 hover:text-red-700 ml-4"
          >
            删除
          </button>
        </div>
      </van-checkbox-group>
    </div>
  </div>
  <TabBar class="footer mt-6 fixed bottom-12 w-full">
    <div class="flex justify-between bg-white mt-4 px-4 py-2 rouned-sm">
      <div class="mb-4 flex items-center mt-3 text-base">
        <van-checkbox
          v-model="isCheckAll"
          :indeterminate="isIndeterminate"
          @change="checkAllChange"
        >
          <span class="text-slate-400">全选</span>
        </van-checkbox>
      </div>
      <div class="flex items-center">
        <div class="text-base text-slate-400 flex mr-1">
          <span>合计：</span>
          <p class="text-red-500 text-xl font-semibold">
            {{ getCurrency(totalPrice) }}
          </p>
        </div>
        <button
          @click="checkout"
          class="bg-orange-500 text-white py-2 px-4 rounded-3xl hover:bg-orange-600 ml-1"
        >
          结算
        </button>
      </div>
    </div>
  </TabBar>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
// 工具函数库
import { getCurrency } from "../../utils/utils";
// import '../utils/WatfulFull'
// ts 里比js复杂
// 数据
import axios from "../../api/index";
import type { ViewItem } from "../../types/home";

let ViewStateRef = ref([]);

onMounted(async () => {
  try {
    const response = await axios.get("/findShop");
    ViewStateRef.value = response.data;
    cartItems.value = ViewStateRef.value.slice(0, 4);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
});

let cartItems = ref<ViewItem[]>([]);
// 定义响应式变量
const manageMode = ref(false);
const isCheckAll = ref(false);
const checkedResult = ref([]);
const isIndeterminate = ref(true);
const isEditMode = ref(false);

// 计算购物车商品总数
const cartItemCount = computed(() => cartItems.value.length);

// 计算购物车总价（仅选中的商品）
const totalPrice = computed(() => {
  return cartItems.value
    .filter((item) => checkedResult.value.includes(item.id))
    .reduce((total, item) => total + item.price * item.quantity, 0);
});

// 切换管理模式
const toggleManageMode = () => {
  manageMode.value = !manageMode.value;
};

// 切换全选状态
const checkAllChange = (val: boolean) => {
  checkedResult.value = val ? cartItems.value.map((item) => item.id) : [];
  isIndeterminate.value = false;
};

const checkedResultChange = (value: string[]) => {
  const checkedCount = value.length;
  isCheckAll.value = checkedCount === cartItems.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < cartItems.value.length;
};

// 从购物车中移除商品
const removeFromCart = (productId: number) => {
  cartItems.value = cartItems.value.filter((item) => item.id !== productId);
  checkedResult.value = checkedResult.value.filter((id) => id !== productId);
};

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
};
// 增加商品数量
const increaseQuantity = (product: { quantity: number }) => {
  product.quantity++;
};

// 减少商品数量
const decreaseQuantity = (product: { quantity: number }) => {
  if (product.quantity > 1) {
    product.quantity--;
  }
};

// 结算操作
const checkout = () => {
  alert("结算功能尚未实现");
};
</script>

<style scoped>
/* 如果需要，可以在这里添加额外的样式 */
</style>
